<template>
  <view class="page">
    <!-- 退款状态卡片 -->
    <view class="status-card" :style="{ background: getRefundStatusGradient(order.refundStatus) }">
      <text class="status-icon">{{ getRefundStatusIcon(order.refundStatus) }}</text>
      <text class="status-text">{{ getRefundStatusText(order.refundStatus) }}</text>
      <text class="status-desc">{{ getRefundStatusDesc(order.refundStatus) }}</text>
    </view>

    <!-- 订单信息 -->
    <view class="section order-info">
      <view class="section-title">
        <text class="title-icon">📋</text>
        <text class="title-text">订单信息</text>
      </view>
      <view class="info-content">
        <view class="info-item">
          <text class="info-label">订单号</text>
          <text class="info-value">{{ order.orderNo }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">订单类型</text>
          <text class="info-value">{{ getOrderTypeText(order.orderType) }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">订单金额</text>
          <text class="info-value">¥{{ order.actualAmount }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">收货地址</text>
          <text class="info-value">{{ order.deliveryAddress || '无' }}</text>
        </view>
        <view class="info-item" v-if="order.refundApplyTime">
          <text class="info-label">申请时间</text>
          <text class="info-value">{{ formatTime(order.refundApplyTime) }}</text>
        </view>
        <view class="info-item" v-if="order.cancelReason">
          <text class="info-label">取消原因</text>
          <text class="info-value">{{ order.cancelReason }}</text>
        </view>
      </view>
    </view>

    <!-- 退款信息 -->
    <view class="section refund-info" v-if="order.refundStatus > 0">
      <view class="section-title">
        <text class="title-icon">💰</text>
        <text class="title-text">退款信息</text>
      </view>
      <view class="info-content">
        <view class="info-item" v-if="order.refundAmount">
          <text class="info-label">退款金额</text>
          <text class="info-value highlight">¥{{ order.refundAmount }}</text>
        </view>
        <view class="info-item" v-if="order.compensationAmount && order.compensationAmount > 0">
          <text class="info-label">补偿金额</text>
          <text class="info-value">¥{{ order.compensationAmount }}</text>
        </view>
        <view class="info-item" v-if="order.refundRejectReason">
          <text class="info-label">拒绝原因</text>
          <text class="info-value">{{ order.refundRejectReason }}</text>
        </view>
      </view>
    </view>

    <!-- 审核操作（仅待审核状态显示） -->
    <view class="section approval-section" v-if="order.refundStatus === 1 && !readonly">
      <view class="section-title">
        <text class="title-icon">⚖️</text>
        <text class="title-text">审核操作</text>
      </view>
      
      <!-- 代取订单补偿比例设置 -->
      <view class="compensation-setting" v-if="order.orderType !== 1">
        <view class="setting-title">
          <text class="title-text">补偿比例设置</text>
          <text class="title-desc">（给接单人的补偿）</text>
        </view>
        <view class="rate-options">
          <view 
            class="rate-item" 
            :class="{ active: selectedRate === rate.value }"
            v-for="rate in rateOptions" 
            :key="rate.value"
            @click="selectRate(rate.value)"
          >
            <text class="rate-text">{{ rate.label }}</text>
            <text class="rate-desc">{{ rate.value === 'custom' ? '自定义金额' : '补偿¥' + ((order.actualAmount || 0) * rate.value).toFixed(2) }}</text>
          </view>
        </view>
        
        <!-- 自定义比例 -->
        <view class="custom-rate" v-if="showCustomRate">
          <view class="rate-input-group">
            <text class="input-label">自定义比例：</text>
            <input 
              class="rate-input"
              type="number"
              v-model="customRate"
              placeholder="10-50"
              @input="onCustomRateInput"
            />
            <text class="input-unit">%</text>
          </view>
          <text class="rate-preview">补偿金额：¥{{ customCompensationAmount }}</text>
        </view>
      </view>

    </view>

    <!-- 拒绝原因输入 -->
    <view class="section reject-reason-section" v-if="showRejectReason">
      <view class="section-title">
        <text class="title-icon">✏️</text>
        <text class="title-text">拒绝原因</text>
      </view>
      <view class="reject-reason">
        <textarea 
          class="reason-input"
          v-model="rejectReason"
          placeholder="请说明拒绝退款的原因..."
          maxlength="200"
        ></textarea>
        <text class="char-count">{{ rejectReason.length }}/200</text>
        
        <!-- 拒绝确认按钮 -->
        <view class="reject-actions">
          <view class="btn btn-cancel" @click="cancelReject">取消</view>
          <view 
            class="btn btn-confirm-reject" 
            :class="{ disabled: submitting }"
            @click="submitting ? null : submitReject"
          >
            {{ submitting ? '处理中...' : '确认拒绝' }}
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar" v-if="order.refundStatus === 1 && !readonly && !showRejectReason">
      <view 
        class="btn btn-reject" 
        :class="{ disabled: submitting }"
        @click="handleReject"
      >
        {{ submitting ? '处理中...' : '拒绝退款' }}
      </view>
      <view 
        class="btn btn-approve" 
        :class="{ disabled: submitting }"
        @click="handleApprove"
      >
        {{ submitting ? '处理中...' : '同意退款' }}
      </view>
    </view>
    
    <!-- 只读模式底部栏 -->
    <view class="bottom-bar" v-else-if="!showRejectReason">
      <view class="btn btn-default" @click="goBack">返回</view>
    </view>
  </view>
</template>

<script>
import { getRefundStatus, approveRefund } from '@/api/refund'
import { getOrderTypeText } from '@/utils/orderStatus'

export default {
  data() {
    return {
      orderId: null,
      order: {},
      readonly: false,
      action: '', // approve, reject
      
      // 补偿比例选项
      selectedRate: 0.2, // 默认20%
      rateOptions: [
        { label: '10%', value: 0.1 },
        { label: '20%', value: 0.2 },
        { label: '30%', value: 0.3 },
        { label: '50%', value: 0.5 },
        { label: '自定义', value: 'custom' }
      ],
      showCustomRate: false,
      customRate: '',
      
      // 拒绝原因
      showRejectReason: false,
      rejectReason: '',
      
      submitting: false
    }
  },
  computed: {
    customCompensationAmount() {
      const rate = parseFloat(this.customRate) / 100
      if (isNaN(rate) || rate < 0.1 || rate > 0.5) return '0.00'
      return ((this.order.actualAmount || 0) * rate).toFixed(2)
    }
  },
  onLoad(options) {
    if (options.orderId) {
      this.orderId = options.orderId
      this.readonly = options.readonly === 'true'
      this.action = options.action || ''
      this.loadRefundDetail()
    }
  },
  methods: {
    async loadRefundDetail() {
      try {
        uni.showLoading({ title: '加载中...' })
        const response = await getRefundStatus(this.orderId)
        //console.log('退款详情响应:', response)
        
        // 根据规范，请求拦截器已经返回了data字段的内容
        if (response) {
          this.order = response
          //console.log('订单数据:', this.order)
          //console.log('退款状态:', this.order.refundStatus, '订单类型:', this.order.orderType, '只读模式:', this.readonly)
        } else {
          throw new Error('订单数据为空')
        }
        
        // 根据action自动展开对应操作
        if (this.action === 'reject') {
          this.showRejectReason = true
        }
        
        uni.hideLoading()
      } catch (error) {
        console.error('加载退款详情失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      }
    },

    selectRate(rate) {
      //console.log('选择比例:', rate)
      this.selectedRate = rate
      this.showCustomRate = rate === 'custom'
      if (rate !== 'custom') {
        this.customRate = ''
      }
      //console.log('当前选中比例:', this.selectedRate, '显示自定义:', this.showCustomRate)
    },

    onCustomRateInput() {
      const rate = parseFloat(this.customRate)
      if (rate < 10) {
        this.customRate = '10'
      } else if (rate > 50) {
        this.customRate = '50'
      }
    },

    handleReject() {
      if (this.submitting) {
        return
      }
      
      this.showRejectReason = true
      this.showCustomRate = false
    },

    // 提交拒绝退款
    submitReject() {
      if (!this.rejectReason.trim()) {
        uni.showToast({
          title: '请填写拒绝原因',
          icon: 'none'
        })
        return
      }
      
      this.submitApproval(false, null, this.rejectReason.trim())
    },

    // 取消拒绝
    cancelReject() {
      this.showRejectReason = false
      this.rejectReason = ''
    },

    handleApprove() {
      if (this.submitting) {
        //console.log('正在提交中，忽略点击')
        return
      }
      
      //console.log('点击同意退款按钮')
      //console.log('订单类型:', this.order.orderType, '选中比例:', this.selectedRate)
      
      // 清空拒绝理由和隐藏拒绝输入框
      this.rejectReason = ''
      this.showRejectReason = false
      
      if (this.order.orderType === 1) {
        // 零食订单直接同意
        this.submitApproval(true, null, '')
      } else {
        // 代取订单需要设置补偿比例
        let compensationRate = this.selectedRate
        if (this.selectedRate === 'custom') {
          compensationRate = parseFloat(this.customRate) / 100
          if (isNaN(compensationRate) || compensationRate < 0.1 || compensationRate > 0.5) {
            uni.showToast({
              title: '请输入10-50之间的补偿比例',
              icon: 'none'
            })
            return
          }
        }
        
        this.submitApproval(true, compensationRate, '')
      }
    },

    async submitApproval(approved, compensationRate, rejectReason) {
      if (!approved && !rejectReason.trim()) {
        uni.showToast({
          title: '请填写拒绝原因',
          icon: 'none'
        })
        return
      }

      try {
        this.submitting = true
        uni.showLoading({ title: '处理中...' })
        
        const params = {
          orderId: this.orderId,
          approved,
          compensationRate,
          rejectReason: rejectReason.trim(),
          orderAmount: this.order.actualAmount
        }
        
        const response = await approveRefund(params)
        
        uni.hideLoading()
        
        //console.log('审核响应:', response)
        
        this.submitting = false
        
        uni.showModal({
          title: approved ? '退款已同意' : '退款已拒绝',
          content: response?.message || '处理完成',
          showCancel: false,
          confirmText: '确定',
          success: () => {
            // 返回列表页面
            uni.navigateBack()
          }
        })
        
      } catch (error) {
        console.error('处理退款失败:', error)
        this.submitting = false
        uni.hideLoading()
        
        // 提取友好的错误信息
        let errorMessage = '处理失败'
        
        if (error.message) {
          const message = error.message
          
          // 尝试提取微信返回的友好错误信息
          if (message.includes('基本账户余额不足')) {
            errorMessage = '微信商户账户余额不足，请充值后重试'
          } else if (message.includes('NOT_ENOUGH')) {
            errorMessage = '商户账户余额不足，无法处理退款'
          } else if (message.includes('申请退款失败')) {
            // 尝试从错误信息中提取具体原因
            const match = message.match(/申请退款失败：(.+?)(?:\n|$|httpResponse)/);
            if (match && match[1]) {
              errorMessage = `退款失败：${match[1]}`
            } else {
              errorMessage = '申请退款失败，请稍后重试'
            }
          } else if (message.includes('Wrong HttpStatusCode')) {
            errorMessage = '微信支付接口调用失败，请稍后重试'
          } else {
            // 如果错误信息太长，截取前100个字符
            errorMessage = message.length > 100 ? message.substring(0, 100) + '...' : message
          }
        }
        
        uni.showModal({
          title: '退款处理失败',
          content: errorMessage,
          showCancel: false,
          confirmText: '我知道了'
        })
      }
    },

    goBack() {
      uni.navigateBack()
    },

    formatTime(timeStr) {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },

    getRefundStatusText(status) {
      const statusMap = {
        0: '无退款',
        1: '待审核',
        2: '已同意',
        3: '已拒绝'
      }
      return statusMap[status] || '未知状态'
    },

    getRefundStatusIcon(status) {
      const iconMap = {
        0: '📋',
        1: '⏳',
        2: '✅',
        3: '❌'
      }
      return iconMap[status] || '❓'
    },

    getRefundStatusDesc(status) {
      const descMap = {
        0: '该订单未申请退款',
        1: '用户申请退款，等待您的审核',
        2: '退款已同意并处理',
        3: '退款申请已被拒绝'
      }
      return descMap[status] || ''
    },

    getRefundStatusGradient(status) {
      const gradientMap = {
        0: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        1: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
        2: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
        3: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)'
      }
      return gradientMap[status] || gradientMap[0]
    },

    getOrderTypeText
  }
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f5f7fa;
  padding-bottom: 180rpx;
}

/* 状态卡片 */
.status-card {
  padding: 60rpx 32rpx;
  text-align: center;
  color: #fff;
  
  .status-icon {
    font-size: 80rpx;
    display: block;
    margin-bottom: 24rpx;
  }
  
  .status-text {
    font-size: 36rpx;
    font-weight: 600;
    display: block;
    margin-bottom: 16rpx;
  }
  
  .status-desc {
    font-size: 28rpx;
    opacity: 0.9;
    display: block;
  }
}

/* 通用样式 */
.section {
  background: #fff;
  margin: 20rpx 32rpx;
  border-radius: 16rpx;
  overflow: hidden;
}

.section-title {
  display: flex;
  align-items: center;
  padding: 32rpx;
  border-bottom: 1px solid #f0f0f0;
  
  .title-icon {
    font-size: 32rpx;
    margin-right: 16rpx;
  }
  
  .title-text {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
  }
}

.info-content {
  padding: 32rpx;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.info-label {
  font-size: 30rpx;
  color: #666;
  width: 160rpx;
  flex-shrink: 0;
}

.info-value {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
  flex: 1;
  text-align: right;
  word-break: break-all;
  
  &.highlight {
    color: #ff6b35;
    font-weight: 600;
  }
}

/* 审核操作 */
.approval-section {
  .compensation-setting {
    padding: 32rpx;
    border-bottom: 1px solid #f0f0f0;
    
    .setting-title {
      margin-bottom: 24rpx;
      
      .title-text {
        font-size: 30rpx;
        color: #333;
        font-weight: 600;
      }
      
      .title-desc {
        font-size: 26rpx;
        color: #999;
        margin-left: 8rpx;
      }
    }
    
    .rate-options {
      display: flex;
      flex-wrap: wrap;
      gap: 16rpx;
      margin-bottom: 24rpx;
    }
    
    .rate-item {
      flex: 1;
      min-width: 140rpx;
      padding: 20rpx 16rpx;
      border: 2rpx solid #e0e0e0;
      border-radius: 12rpx;
      text-align: center;
      
      &.active {
        border-color: #ff6b35;
        background: #fff3e0;
        
        .rate-text {
          color: #ff6b35;
        }
      }
      
      .rate-text {
        font-size: 28rpx;
        color: #333;
        font-weight: 600;
        display: block;
        margin-bottom: 8rpx;
      }
      
      .rate-desc {
        font-size: 24rpx;
        color: #666;
      }
    }
    
    .custom-rate {
      .rate-input-group {
        display: flex;
        align-items: center;
        margin-bottom: 16rpx;
        
        .input-label {
          font-size: 28rpx;
          color: #333;
          margin-right: 16rpx;
        }
        
        .rate-input {
          flex: 1;
          height: 60rpx;
          padding: 0 16rpx;
          border: 1px solid #e0e0e0;
          border-radius: 8rpx;
          font-size: 28rpx;
          text-align: center;
        }
        
        .input-unit {
          font-size: 28rpx;
          color: #666;
          margin-left: 16rpx;
        }
      }
      
      .rate-preview {
        font-size: 26rpx;
        color: #ff6b35;
        font-weight: 600;
      }
    }
  }
}

/* 独立的拒绝原因输入区域 */
.reject-reason-section {
  .reject-reason {
    padding: 32rpx;
    
    .reason-input {
      width: 100%;
      min-height: 200rpx;
      padding: 24rpx;
      border: 1px solid #e0e0e0;
      border-radius: 12rpx;
      font-size: 28rpx;
      color: #333;
      background: #fafafa;
      box-sizing: border-box;
    }
    
    .char-count {
      display: block;
      text-align: right;
      margin-top: 16rpx;
      font-size: 24rpx;
      color: #999;
    }
    
    .reject-actions {
      display: flex;
      gap: 24rpx;
      margin-top: 32rpx;
      
      .btn {
        flex: 1;
        height: 72rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 36rpx;
        font-size: 28rpx;
        font-weight: 600;
        
        &.btn-cancel {
          background: #f5f5f5;
          color: #666;
        }
        
        &.btn-confirm-reject {
          background: linear-gradient(135deg, #ff4757 0%, #ff3742 100%);
          color: #fff;
        }
        
        &.disabled {
          opacity: 0.6;
          pointer-events: none;
        }
      }
    }
  }
}

/* 底部操作栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 32rpx;
  background: #fff;
  border-top: 1px solid #e0e0e0;
  gap: 24rpx;
}

.btn {
  flex: 1;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: 600;
  
  &.btn-default {
    background: #f0f0f0;
    color: #666;
  }
  
  &.btn-reject {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-approve {
    background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
    color: #fff;
  }
}
</style>
